package com.lunasoft.nettyniodemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Jierry
 * @version 2016/7/5.
 */
public class TimeServer {

    public void bind(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); //定义管理客户端连接的线程组
        EventLoopGroup workGroup = new NioEventLoopGroup(); //定义处理网络读写的工作线程组
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();//Netty的辅助启动类
            serverBootstrap.group(bossGroup, workGroup) //传递2个工作组
                    .channel(NioServerSocketChannel.class) //定义创建的Channel方式,此处对应NIO库中的ServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG, 1024) //设置backlog为1024
                    .childHandler(new ServerInitializer()); //绑定IO事件的处理类

            ChannelFuture f = serverBootstrap.bind(port).sync(); //绑定端口，调用同步阻塞方法sync等待绑定操作完成
            f.channel().closeFuture().sync();//进行阻塞，等待服务器链路关闭之后main函数才退出
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 9097;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {

            }
        }
        new TimeServer().bind(port);
    }
}
